<?php


class ArticleService extends Service
{
  /**
   * @param string $className
   * @return ArticleService
   */
  public static function instance($className = __CLASS__)
  {
    return parent::instance($className);
  }

  /**
   * 获取文章列表
   * @param int $pageSize 分页大小
   * @param int $lesson_id 课程编号
   * @param bool $with 关联
   * @param string $keywords 关键词
   * @return array
   */
  public function getList($pageSize = 20, $lesson_id = 0, $with = true, $keywords = '')
  {
    $criteria = new CDbCriteria();
    $criteria->condition = 'article.lesson_id=:lesson_id';
    $criteria->params = array(':lesson_id' => $lesson_id);
    //关键字
    if (!empty($keywords)) {
      $criteria->addSearchCondition('title', $keywords);
    }
    //关联
    if ($with) {
      $criteria->with = array(
          'lesson'
      );
    }
    $criteria->order = 'article.hits desc,article.created_at desc';
    $count = Article::model()->count($criteria);
    $pages = new CPagination($count);
    $pages->pageSize = $pageSize;
    $pages->applyLimit($criteria);
    $criteria->offset = $pages->currentPage * $pages->pageSize;
    $list = Article::model()->findAll($criteria);
    return array(
        'list' => $list,
        'pages' => $pages
    );
  }

  /**
   * 清除文章缓存
   * @param int $article_id
   */
  private function clearCache($article_id = 0)
  {
    $keys = array(
        'article-content-with-' . $article_id,
        'article-content-' . $article_id,
        'article-prev-' . $article_id,
        'article-next-' . $article_id
    );
    foreach ($keys as $key) {
      Yii::app()->cache->set($key, false);
    }
  }

  /**
   * 添加/编辑文章
   * @param array $data 文章数据
   * @param int $user_id 创建者ID(编辑时凭证)
   * @return array|bool|string
   */
  public function post($data = array(), $user_id = 0)
  {
    if (empty($data['article_id'])) {
      $article = new Article();
    } else {
      $article = Article::model()->with('lesson')->findByPk($data['article_id']);
      if ($article->lesson->user_id != $user_id) {
        return '对不起，该文章所属课程不是你创建的!';
      }
    }
    $article->attributes = $data;
    if ($article->save()) {
      $this->clearCache($article->article_id);
    } else {
      return $article->errors;
    }
  }

  /**
   * 删除文章
   * @param array $list
   * @return array|bool
   */
  public function delete($list = array())
  {
    $criteria = new CDbCriteria();
    $criteria->addInCondition('article_id', $list);
    return Article::model()->deleteAll($criteria) ? true : false;
  }

  /**
   * 点击数+1
   * @param int $article_id
   */
  public function hits($article_id = 0)
  {
    if (Yii::app()->user->isGuest) {
      //游客，利用IP
      $key = 'article-' . $article_id . '-ip-' . Yii::app()->request->userHostAddress;
    } else {
      //用户，利用userid
      $key = 'article-' . $article_id . '-user-id-' . Yii::app()->user->id;
    }
    $data = Yii::app()->cache->get($key);
    if ($data === false) {
      $article = Article::model()->findByPk($article_id);
      $article->hits++;
      $article->save();
      Yii::app()->cache->set($key, 1);
    }
  }

  /**
   * 获取文章信息
   * @param int $article_id
   * @param bool $with
   * @return CActiveRecord|mixed
   */
  public function view($article_id = 0, $with = false)
  {
    $key = $with == true ? 'article-content-with-' . $article_id : 'article-content-' . $article_id;
    $data = Yii::app()->cache->get($key);
    if ($data === false) {
      $criteria = new CDbCriteria();
      $criteria->condition = 'article_id=:article_id';
      $criteria->params = array(':article_id' => $article_id);
      if ($with) {
        $criteria->with = array(
            'lesson'
        );
      }
      $data = Article::model()->find($criteria);
      Yii::app()->cache->set($key, $data, 3600 * 24 * 7);
    }
    return $data;
  }

  /**
   * 获取文章课程ID
   * @param int $article_id
   * @return mixed
   */
  private function getLessonIdByArticleId($article_id = 0)
  {
    $key = 'article-content-' . $article_id;
    $data = Yii::app()->cache->get($key);
    if ($data === false) {
      $criteria = new CDbCriteria();
      $criteria->condition = 'article_id=:article_id';
      $criteria->params = array(':article_id' => $article_id);
      $data = Article::model()->find($criteria);
      Yii::app()->cache->set($key, $data, 3600 * 24 * 7);
    }
    return $data->lesson_id;
  }

  /**
   * 上一篇
   * @param int $article_id
   * @return CActiveRecord|mixed
   */
  public function prev($article_id = 0)
  {
    $key = 'article-prev-' . $article_id;
    $data = Yii::app()->cache->get($key);
    if ($data === false) {
      //查询文章所属lesson
      $lesson_id = $this->getLessonIdByArticleId($article_id);
      $criteria = new CDbCriteria();
      $criteria->condition = 'article_id < :article_id and lesson_id = :lesson_id';
      $criteria->order = 'article_id desc';
      $criteria->limit = 1;
      $criteria->params = array(':article_id' => $article_id, ':lesson_id' => $lesson_id);
      $data = Article::model()->find($criteria);
      Yii::app()->cache->set($key, $data, 3600 * 24 * 7);
    }
    return $data;
  }

  /**
   * 下一篇
   * @param int $article_id
   * @return CActiveRecord|mixed
   */
  public function next($article_id = 0)
  {
    $key = 'article-next-' . $article_id;
    $data = Yii::app()->cache->get($key);
    if ($data === false) {
      //查询文章所属lesson
      $lesson_id = $this->getLessonIdByArticleId($article_id);
      $criteria = new CDbCriteria();
      $criteria->condition = 'article_id > :article_id and lesson_id = :lesson_id';
      $criteria->order = 'article_id asc';
      $criteria->limit = 1;
      $criteria->params = array(':article_id' => $article_id, ':lesson_id' => $lesson_id);
      $data = Article::model()->find($criteria);
      Yii::app()->cache->set($key, $data, 3600 * 24 * 7);
    }
    return $data;
  }
} 